package com.dashu.core.service;

import com.dashu.base.enums.ReplRyCode;
import com.dashu.base.utils.CopyUtil;
import com.dashu.base.utils.UIDUtil;
import com.dashu.base.utils.VerificationUtil;
import com.dashu.core.dto.attendance.AttendanceDateDTO;
import com.dashu.core.dto.attendance.AttendanceTimeDTO;
import com.dashu.core.dto.company.CompanyDTO;
import com.dashu.core.handler.VerificationException;
import com.dashu.core.model.AttendanceTime;
import com.dashu.core.model.QAttendanceTime;
import com.dashu.core.result.PageEnty;
import com.dashu.core.vo.UpdateEntityVO;
import com.dashu.core.vo.attendancek.AttendanceTimeListVO;
import com.dashu.core.vo.attendancek.AttendanceTimeVO;
import com.querydsl.core.BooleanBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.FlushModeType;
import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AttendanceTimeService extends DataService {
    @Autowired
    private AttendanceDateService attendanceDateService;
    @Autowired
    private CompanyService companyService;

    @Transactional
    public AttendanceTimeDTO add(AttendanceTimeVO attendancekDateVO) {
        AttendanceTime attendanceTime = CopyUtil.copyEnty(attendancekDateVO, AttendanceTime.class);
        try {
            long userId = Long.parseLong(VerificationUtil.getUserId());
            attendanceTime.setId(UIDUtil.nextId());
            attendanceTime.setCreateUser(userId);
            attendanceTime.setCreateTime(System.currentTimeMillis());
            attendanceTime.setIsDefult(1);
            entityManager.persist(attendanceTime);
//            entityManager.flush();
            entityManager.setFlushMode(FlushModeType.AUTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new VerificationException(ReplRyCode.DATA_NOT_INVALID, ReplRyCode.DATA_NOT_INVALID.getMessage());
        }
        AttendanceTimeDTO attendancekDateDTO = CopyUtil.copyEnty(attendanceTime, AttendanceTimeDTO.class);
        return attendancekDateDTO;

    }

    @Transactional
    public AttendanceTimeDTO addDefult(long baseId) {
        AttendanceTime attendanceTime = new AttendanceTime();
        try {
            long userId = Long.parseLong(VerificationUtil.getUserId());
            attendanceTime.setId(UIDUtil.nextId());
            attendanceTime.setCreateUser(userId);
            attendanceTime.setCreateTime(System.currentTimeMillis());
            attendanceTime.setBaseId(baseId);
            attendanceTime.setIsDefult(0);
            attendanceTime.setStartDate1("08:00");
            attendanceTime.setEndDate1("11:00");
            attendanceTime.setStartDate2("14:00");
            attendanceTime.setEndDate2("18:00");
            attendanceTime.setStartDate3("19:00");
            attendanceTime.setEndDate3("21:00");
            attendanceTime.setName("默认考勤");
            attendanceTime.setOpen("1,1,1");
            entityManager.persist(attendanceTime);
//            entityManager.flush();
            entityManager.setFlushMode(FlushModeType.AUTO);
        } catch (Exception e) {
            e.printStackTrace();
            throw new VerificationException(ReplRyCode.DATA_NOT_INVALID, ReplRyCode.DATA_NOT_INVALID.getMessage());
        }
        AttendanceTimeDTO attendancekDateDTO = CopyUtil.copyEnty(attendanceTime, AttendanceTimeDTO.class);
        return attendancekDateDTO;

    }

    @Transactional
    public boolean deleteAttendancekData(long timeId) {
        QAttendanceTime qAttendanceTime = QAttendanceTime.attendanceTime;
        List<AttendanceDateDTO> attendanceDateDTOS = attendanceDateService.findAttendanceTime(timeId);
        if (attendanceDateDTOS.size() > 0)
            throw new VerificationException(ReplRyCode.ATTENDANCE_RULE_TIME, ReplRyCode.ATTENDANCE_RULE_TIME.getMessage());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qAttendanceTime.id.eq(timeId));

        List<AttendanceTime> attendanceTimes =
                queryFactory
                        .select(qAttendanceTime)
                        .from(qAttendanceTime)
                        .where(booleanBuilder.getValue())
                        .fetch();
        attendanceTimes.stream().forEach(ad -> {
            entityManager.remove(ad);
//            entityManager.flush();
            entityManager.setFlushMode(FlushModeType.AUTO);
        });
        return true;

    }

    @Transactional
    public AttendanceTimeDTO updataAttendanceData(UpdateEntityVO<AttendanceTimeVO> attendancekDateVO) throws Exception {
        QAttendanceTime qAttendanceTime = QAttendanceTime.attendanceTime;
        long userId = Long.parseLong(VerificationUtil.getUserId());
        AttendanceTimeVO attendanceTimeVO = attendancekDateVO.getEntityVO();
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qAttendanceTime.id.eq(attendancekDateVO.getId()));
        AttendanceTime attendanceTime =
                queryFactory
                        .select(qAttendanceTime)
                        .from(qAttendanceTime)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        if (attendanceTime == null)
            throw new VerificationException(ReplRyCode.ATTENDANCE_NOT_TIME, ReplRyCode.ATTENDANCE_NOT_TIME.getMessage());
        if (!StringUtils.isEmpty(attendanceTimeVO.getStartDate1()))
            attendanceTime.setStartDate1(attendanceTimeVO.getStartDate1());
        if (!StringUtils.isEmpty(attendanceTimeVO.getStartDate2()))
            attendanceTime.setStartDate2(attendanceTimeVO.getStartDate2());
        if (!StringUtils.isEmpty(attendanceTimeVO.getStartDate3()))
            attendanceTime.setStartDate3(attendanceTimeVO.getStartDate3());
        if (!StringUtils.isEmpty(attendanceTimeVO.getEndDate1()))
            attendanceTime.setEndDate1(attendanceTimeVO.getEndDate1());
        if (!StringUtils.isEmpty(attendanceTimeVO.getEndDate2()))
            attendanceTime.setEndDate2(attendanceTimeVO.getEndDate2());
        if (!StringUtils.isEmpty(attendanceTimeVO.getEndDate3()))
            attendanceTime.setEndDate3(attendanceTimeVO.getEndDate3());
        if (!StringUtils.isEmpty(attendanceTimeVO.getName()))
            attendanceTime.setName(attendanceTimeVO.getName());
        if (!StringUtils.isEmpty(attendanceTimeVO.getOpen()))
            attendanceTime.setOpen(attendanceTimeVO.getOpen());
        attendanceTime.setUpdateUser(userId);
        attendanceTime.setUpdateTime(new Date().getTime());
        attendanceTime = entityManager.merge(attendanceTime);
        entityManager.setFlushMode(FlushModeType.AUTO);
        AttendanceTimeDTO CompanyClsDTO = CopyUtil.copyEnty(attendanceTime, AttendanceTimeDTO.class);
        return CompanyClsDTO;

    }


    public AttendanceTimeDTO findAttendancekGroup(long timeId) {
        QAttendanceTime qAttendanceTime = QAttendanceTime.attendanceTime;
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qAttendanceTime.id.eq(timeId));
        AttendanceTime attendanceTime =
                queryFactory
                        .select(qAttendanceTime)
                        .from(qAttendanceTime)
                        .where(booleanBuilder.getValue())
                        .fetchOne();
        AttendanceTimeDTO attendanceTimeDTO = CopyUtil.copyEnty(attendanceTime, AttendanceTimeDTO.class);
        return attendanceTimeDTO;

    }

    public long count(PageEnty<AttendanceTimeListVO> attendanceTimeVO) throws Exception {
        QAttendanceTime qAttendanceTime = QAttendanceTime.attendanceTime;
        AttendanceTimeListVO attendanceTimeListVO = attendanceTimeVO.getVo();
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qAttendanceTime.createUser.eq(userId));
        if (attendanceTimeVO.getBaseId() != 0)
            booleanBuilder.and(qAttendanceTime.baseId.eq(attendanceTimeVO.getBaseId()));
        if (!StringUtils.isEmpty(attendanceTimeListVO.getTimeName()))
            booleanBuilder.and(qAttendanceTime.name.like("%" + attendanceTimeListVO.getTimeName() + "%"));
        long count =
                queryFactory
                        .select(qAttendanceTime)
                        .from(qAttendanceTime)
                        .where(booleanBuilder.getValue())
                        .fetchCount();
        return count;

    }

    public List<AttendanceTimeDTO> findTimeList(PageEnty<AttendanceTimeListVO> attendanceTimeVO) throws Exception {
        QAttendanceTime qAttendanceTime = QAttendanceTime.attendanceTime;
        AttendanceTimeListVO attendanceTimeListVO = attendanceTimeVO.getVo();
        long userId = Long.parseLong(VerificationUtil.getUserId());
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qAttendanceTime.createUser.eq(userId));
        if (attendanceTimeVO.getBaseId() != 0)
            booleanBuilder.and(qAttendanceTime.baseId.eq(attendanceTimeVO.getBaseId()));
        if (!StringUtils.isEmpty(attendanceTimeListVO.getTimeName()))
            booleanBuilder.and(qAttendanceTime.name.like("%" + attendanceTimeListVO.getTimeName() + "%"));
        List<AttendanceTime> attendanceTimes =
                queryFactory
                        .select(qAttendanceTime)
                        .from(qAttendanceTime)
                        .where(booleanBuilder.getValue())
                        .orderBy(qAttendanceTime.createTime.desc())
                        .fetch();
        List<AttendanceTimeDTO> attendanceTimeDTOS = CopyUtil.copyList(attendanceTimes, AttendanceTimeDTO.class);
        attendanceTimeDTOS.stream().forEach(atd -> {
            CompanyDTO companyDTO = companyService.findByCompanyId(atd.getBaseId());
            atd.setBaseName(companyDTO.getCompanyName());
        });
        return attendanceTimeDTOS;

    }

}
